#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command.handler import dict_handler
from command import command
import logging,os
from utility import tools
from utility.memcache_manager import MemcacheManager
import pandas as pd
from settings  import DOWN_FILE_DIR
from utility.file_split import split_file

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class DeliveryDetailsListAPI(Resource):
    """
    产科分娩明细表
    :request: post
    :param fmsjStart: 分娩时间开始日期
    :param fmsjEnd: 分娩时间结束日期
    :param fmfs: 分娩方式
    :param csqx: 出生缺陷
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ =  order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            query_ = []
            if params.get('fmsjStart'): # 分娩时间开始日期
                query_.append(('create_date', '>=', params.get('fmsjStart'))) 
            if params.get('fmsjEnd'): # 分娩时间结束日期
                query_.append(('create_date', '<=', params.get('fmsjEnd')))        
            if params.get('fmfs'): # 分娩方式
                query_.append(('decc_fmfs', '=', params.get('fmfs')))  
            #if params.get('csqx'): # 出生缺陷 没找到
            #    query_.append(('cf_fmfs', '=', params.get('csqx')))  
            if params.get('searchText'): # 搜索字符串
                query_t_ = []
                query_t_.append(('mq_xm', 'ilike', int(params.get('searchText'))))  # 孕妇姓名  
                query_t_.append(('mq_sjhm', 'ilike', int(params.get('searchText')))) # 孕妇手机号码  没找到
                query_t_.append(('mq_sfz', 'ilike', int(params.get('searchText')))) # 身份证号
                query_t_.append(('zyh', 'ilike', int(params.get('searchText')))) # 住院号 
                res_archives = odoo.env['res.archives'].search_read(query_t_,['id'])
                if res_archives:
                    archives_ids = [archives['id']  for archives in res_archives]
                    query_.append(('archives_id', 'in', archives_ids))     
            fields = [
                    'id','cf_yz_week','cf_yz_day','cf_yc','create_date',
                    'zz_jsz','archives_id','decc_fmfs','cf_cx'
                    ]        
            records = odoo.env['birth.record'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            data_ = {'dataList': [],'total': 0}   
            data_['total'] = odoo.env['birth.record'].search_count(query_)  
            if records:
                for  record_ in records:
                    query_ = [('id', '=', int(record_['archives_id'][0]))]
                    fields = ['zyh','mq_xm','mq_age','mq_sjhm','mq_hj_address']
                    res_archives = odoo.env['res.archives'].search_read(query_,fields)
                    query_ = [('id', '=', int(record_['archives_id'][0]))]
                    fields = ['ycs_cc']
                    initial_ = odoo.env['inspection.initial'].search_read(query_,fields)
                    query_ = [('main_id', '=', int(record_['id']))]
                    fields = ['dscc_tp','decc_tfw','decc_texb','decc_tetz','decc_tesc']
                    line_ = odoo.env['birth.record.line'].search_read(query_,fields)
                    #print (record_['zz_jsz'])
                    if res_archives:
                        res_archives = res_archives[0]
                        data_tmp = {
                            'bh': record_['id'],
                            'zyh': res_archives['zyh'],
                            'xm': res_archives['mq_xm'],
                            'age': res_archives['mq_age'],
                            'yz': str(record_['cf_yz_week'])+'+'+str(record_['cf_yz_day']),
                            'yc': record_['cf_yc'],
                            'cc': initial_[0]['ycs_cc'] if initial_ else '0',
                            'fmsj': record_['create_date'],
                            'fmfs': dict_handler.get_dict_value(record_['decc_fmfs'],'ck_fmfs'),
                            'tfw': dict_handler.get_dict_value(line_[0]['decc_tfw'],'ck_tfw') if line_ else '',
                            'xll': record_['cf_cx'],
                            'tpqk': dict_handler.get_dict_value(line_[0]['dscc_tp'],'ck_tp') if line_ else '',
                            'sex': dict_handler.get_dict_value(line_[0]['decc_texb'],'sys_user_sex') if line_ else '',
                            'length': line_[0]['decc_tesc']if line_ else '',
                            'weight': line_[0]['decc_tetz']if line_ else '',
                            'pf': '',
                            'csqx': '',
                            'phone': res_archives['mq_sjhm'],
                            'hkAddr': res_archives['mq_hj_address'],
                            'jszName': record_['zz_jsz'][-1] if record_['zz_jsz'] else record_['zz_jsz'],
                            'sfnc': ''
                        }
                    data_['dataList'].append(data_tmp)
            return jsonify({'code': 0, 'msg': 'success', 'data': data_})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DeliveryDetailsExportAPI(Resource):
    """
    导出产科分娩明细表
    :request: post
    :param fmsjStart: 分娩时间开始日期
    :param fmsjEnd: 分娩时间结束日期
    :param fmfs: 分娩方式
    :param csqx: 出生缺陷
    :param searchText: 搜索内容
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            #获取UID
            uid = params.get('uid')
            # 防重校验
            cache = MemcacheManager()
            check = cache.get('delivery_details'+str(uid))
            if check:
                check = check.split(',')
                data_ ={
                        'blob': str(open(check[0], 'rb').read()),
                        'isOver': 0 #0否 1是
                    }
                if len(check)==1:
                    data_['isOver'] = 1   
                    cache.delete('delivery_details'+str(uid)) 
                else:    
                    check = check[1:]    
                    cache.set('delivery_details'+str(uid), ','.join(check))
                return {
                    'code': 0,
                    'data': data_,
                    'msg': 'success',
                } 
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ =  order_by_column+' '+ is_asc
            query_ = []
            if params.get('fmsjStart'): # 分娩时间开始日期
                query_.append(('create_date', '>=', params.get('fmsjStart'))) 
            if params.get('fmsjEnd'): # 分娩时间结束日期
                query_.append(('create_date', '<=', params.get('fmsjEnd')))        
            if params.get('fmfs'): # 分娩方式
                query_.append(('decc_fmfs', '=', params.get('fmfs')))  
            #if params.get('csqx'): # 出生缺陷 没找到
            #    query_.append(('cf_fmfs', '=', params.get('csqx')))  
            if params.get('searchText'): # 搜索字符串
                query_t_ = []
                query_t_.append(('mq_xm', 'ilike', int(params.get('searchText'))))  # 孕妇姓名  
                query_t_.append(('mq_sjhm', 'ilike', int(params.get('searchText')))) # 孕妇手机号码  没找到
                query_t_.append(('mq_sfz', 'ilike', int(params.get('searchText')))) # 身份证号
                query_t_.append(('zyh', 'ilike', int(params.get('searchText')))) # 住院号 
                res_archives = odoo.env['res.archives'].search_read(query_t_,['id'])
                if res_archives:
                    archives_ids = [archives['id']  for archives in res_archives]
                    query_.append(('archives_id', 'in', archives_ids))     
            fields = [
                    'id','cf_yz_week','cf_yz_day','cf_yc','create_date',
                    'zz_jsz','archives_id','decc_fmfs','cf_cx'
                    ]        
            records = odoo.env['birth.record'].search_read(query_,fields, order = order_)

            data_ = []
            if records:
                for  record_ in records:
                    query_ = [('id', '=', int(record_['archives_id'][0]))]
                    fields = ['zyh','mq_xm','mq_age','mq_sjhm','mq_hj_address']
                    res_archives = odoo.env['res.archives'].search_read(query_,fields)
                    query_ = [('id', '=', int(record_['archives_id'][0]))]
                    fields = ['ycs_cc']
                    initial_ = odoo.env['inspection.initial'].search_read(query_,fields)
                    query_ = [('main_id', '=', int(record_['id']))]
                    fields = ['dscc_tp','decc_tfw','decc_texb','decc_tetz','decc_tesc']
                    line_ = odoo.env['birth.record.line'].search_read(query_,fields)
                    #print (record_['zz_jsz'])
                    if res_archives:
                        res_archives = res_archives[0]
                        data_tmp = {
                            '编号': record_['id'],
                            '住院号': res_archives['zyh'],
                            '姓名': res_archives['mq_xm'],
                            '年龄': res_archives['mq_age'],
                            '孕周': str(record_['cf_yz_week'])+'+'+str(record_['cf_yz_day']),
                            '孕次': record_['cf_yc'],
                            '产次': initial_[0]['ycs_cc'] if initial_ else '0',
                            '分娩时间': record_['create_date'],
                            '分娩方式': dict_handler.get_dict_value(record_['decc_fmfs'],'ck_fmfs'),
                            '胎方位': dict_handler.get_dict_value(line_[0]['decc_tfw'],'ck_tfw') if line_ else '',
                            '血流量': record_['cf_cx'],
                            '胎盘情况': dict_handler.get_dict_value(line_[0]['dscc_tp'],'ck_tp') if line_ else '',
                            '性别': dict_handler.get_dict_value(line_[0]['decc_texb'],'sys_user_sex') if line_ else '',
                            '身长': line_[0]['decc_tesc']if line_ else '',
                            '体重': line_[0]['decc_tetz']if line_ else '',
                            '评分': '',
                            '出生缺陷': '',
                            '联系电话': res_archives['mq_sjhm'],
                            '户籍地址': res_archives['mq_hj_address'],
                            '接生者姓名': record_['zz_jsz'][-1] if record_['zz_jsz'] else record_['zz_jsz'],
                            '是否农村': ''
                        }
                    data_.append(data_tmp)
            res = {'blob':'','isOver':'1'}
            #print (res)
            if data_:
                col_names=[
                    '编号','住院号','姓名','年龄','孕周','孕次',
                    '产次','分娩时间','分娩方式','胎方位',
                    '血流量','胎盘情况','性别',
                    '身长','体重','评分',
                    '出生缺陷','联系电话','户籍地址',
                    '接生者姓名','是否农村'
                ]
                df=pd.DataFrame(data_)
                file_path='{}{}-{}-0.xlsx'.format(DOWN_FILE_DIR,'产科分娩明细表',uid)
                df.to_excel(file_path,columns=col_names,index=False)
                file_path_n = split_file('{}-{}-0.xlsx'.format('产科分娩明细表',uid),col_names)
                #初始文件小于3M
                if file_path == file_path_n[0]:
                    res['blob'] = str(open(file_path, 'rb').read())
                    os.remove(file_path)
                else:
                    res['blob'] = str(open(file_path_n[0], 'rb').read()) 
                    os.remove(file_path_n[0])
                    res['isOver'] = '0'
                    #文件大于3M
                    req_flag = ','.join(file_path_n[1:])
                    #文件名保存到缓存里
                    cache.set('delivery_details'+str(uid), req_flag)
            #print (res)
            return jsonify({'code': 0, 'msg': 'success', 'data': res})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})


